package com.wss.service.user.rest;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wss.common.db.*;
import com.wss.common.model.Result;
import com.wss.common.service.TokenService;

import com.wss.service.fegin.CodeService;
import com.wss.service.user.model.vo.UserInfoVo;
import com.wss.service.user.service.IAuthCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

import com.wss.common.redis.*;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {



    @Autowired
    private IAuthCodeService  authCodeService;

    @Resource
    private CodeService codeService;

    @Resource
    private AuthenticationManager authenticationManager;


    @Resource
    private RedisRepository redisRepository ;

    @Resource
    private PasswordEncoder passwordEncoder;
    /**
     * 注册
     * @param userInfoVo
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestBody UserInfoVo userInfoVo){

        int count = authCodeService.count(new LambdaQueryWrapper<AuthCode>()
                .eq(AuthCode::getEmail, userInfoVo.getEmail())
        );
        if(count>0){
            return Result.fail("邮箱已经被使用！");
        }

        Result result = codeService.validate(userInfoVo.getEmail(), userInfoVo.getCode());
        if(result.getCode()==500){
            return  result;
        }
        String encode = passwordEncoder.encode(userInfoVo.getPwd());
        AuthCode authCode = AuthCode.builder().code(userInfoVo.getPwd()).createtime(new Date()).email(userInfoVo.getEmail())
                .expiretime(new Date())
                .password(encode)
                .tenantId("777")
                .username(userInfoVo.getName())
                .build();
        authCodeService.save(authCode);
        return Result.success();
    }


    @GetMapping("isRegistered")
    public  Result isRegistered(@RequestParam("email")String email){
        int count = authCodeService.count(new LambdaQueryWrapper<AuthCode>()
                .eq(AuthCode::getEmail,email)
        );
        if(count>0){
            return Result.fail("邮箱已经被使用！");
        }
        return Result.success();
    }
    @Resource
    private TokenService tokenService;


    /**
     * 登录
     * @param userInfoVo
     * @return
     */
    @PostMapping("login")
    public  Result login(@RequestBody UserInfoVo userInfoVo,
                         HttpServletRequest request, HttpServletResponse response
    ) throws Exception {

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userInfoVo.getName(), userInfoVo.getPwd());
        return  writerToken(request, response, token, "用户名或密码错误");
    }

    private Result writerToken(HttpServletRequest request, HttpServletResponse response, AbstractAuthenticationToken token
            , String badCredenbtialsMsg) throws Exception {
        try {

            Authentication authentication = authenticationManager.authenticate(token);
            AuthCodeInfo user = (AuthCodeInfo) authentication.getPrincipal();
            //System.out.println(user.getTenantId());
            // 生成token
             String token1= tokenService.createToken(user);
             return  Result.success(token1,"");
        }
        catch (Exception e) {
           log.error(e.getMessage(),e);
            return Result.fail(badCredenbtialsMsg);
        }
    }

    @GetMapping("getToken")
    public  Result getToken(@RequestParam("userId")String userId,  HttpServletRequest request, HttpServletResponse response) throws Exception {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("wss", "123456");
        return  writerToken(request, response, token, "用户名或密码错误");
    }

}
